﻿package com.sgcc.nfc.lock.presentation.warnings

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.domain.model.Warning
import com.sgcc.nfc.lock.domain.usecase.GetWarningsUseCase
import com.sgcc.nfc.lock.domain.usecase.HandleWarningUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.launch

@HiltViewModel
class WarningsViewModel @Inject constructor(
    private val getWarningsUseCase: GetWarningsUseCase,
    private val handleWarningUseCase: HandleWarningUseCase
) : ViewModel() {

    private val _warnings = MutableLiveData<List<Warning>>(emptyList())
    val warnings: LiveData<List<Warning>> = _warnings

    private val _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean> = _isLoading

    private val _error = MutableLiveData<String?>()
    val error: LiveData<String?> = _error

    private var currentStatus: Int? = null

    init {
        loadWarnings()
    }

    fun loadWarnings(status: Int? = currentStatus) {
        currentStatus = status
        _isLoading.value = true
        viewModelScope.launch {
            when (val result = getWarningsUseCase(page = 1, pageSize = 50, status = status)) {
                is NetworkResult.Success -> {
                    _warnings.value = result.data.data
                    _error.value = null
                }
                is NetworkResult.Error -> _error.value = result.message
                NetworkResult.Loading -> _isLoading.value = true
            }
            _isLoading.value = false
        }
    }

    fun handleWarning(warningId: Long, remark: String?) {
        viewModelScope.launch {
            when (val result = handleWarningUseCase(warningId, remark)) {
                is NetworkResult.Success -> loadWarnings(currentStatus)
                is NetworkResult.Error -> _error.value = result.message
                NetworkResult.Loading -> _isLoading.value = true
            }
        }
    }
}
